package cn.hd01.web.controller;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.web.PageableDefault;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.hd01.common.BaseConstant;
import cn.hd01.common.BaseConstant.AuditStatus;
import cn.hd01.common.BaseConstant.CustomerType;
import cn.hd01.common.BaseConstant.RebateSummaryType;
import cn.hd01.common.BaseConstant.Status;
import cn.hd01.common.BaseConstant.backendType;
import cn.hd01.common.BaseStatus;
import cn.hd01.common.CustomerLevel;
import cn.hd01.common.Education;
import cn.hd01.common.IntegrationRuleCode;
import cn.hd01.common.Sex;
import cn.hd01.common.Source;
import cn.hd01.model.AuditStatusModel;
import cn.hd01.repository.entity.BankCards;
import cn.hd01.repository.entity.ConsumeReport;
import cn.hd01.repository.entity.Customer;
import cn.hd01.repository.entity.CustomerBankCard;
import cn.hd01.repository.entity.Dictionary;
import cn.hd01.repository.entity.DistributorDetails;
import cn.hd01.repository.entity.DistributorLevel;
import cn.hd01.repository.entity.Integration;
import cn.hd01.repository.entity.IntegrationRuleBook;
import cn.hd01.repository.entity.RebateSummary;
import cn.hd01.repository.entity.Servant;
import cn.hd01.repository.entity.StarReport;
import cn.hd01.repository.entity.TimingSms;
import cn.hd01.repository.entity.User;
import cn.hd01.service.BankCardsService;
import cn.hd01.service.COrderService;
import cn.hd01.service.CustomerBankCardService;
import cn.hd01.service.CustomerService;
import cn.hd01.service.DictionaryService;
import cn.hd01.service.DistributorDetailsService;
import cn.hd01.service.DistributorLevelService;
import cn.hd01.service.IntegrationRuleBookService;
import cn.hd01.service.IntegrationService;
import cn.hd01.service.ProvincesService;
import cn.hd01.service.RebateSummaryService;
import cn.hd01.service.ServantService;
import cn.hd01.service.TimingSmsService;
import cn.hd01.service.UserService;
import cn.hd01.sms.SmsService;
import cn.hd01.util.CommonUtil;
import cn.hd01.util.DictionaryType;
import cn.hd01.web.auth.Auth;
import cn.hd01.web.util.WebConstant;
import cn.hd01.web.util.WebException;

@Controller
@RequestMapping("/customer")
@Auth
public class CustomerController {
	@Autowired
	private CustomerService customerService;
	
	@Autowired
	private DistributorLevelService distributorLevelService;
	
	@Autowired
	private ServantService servantService;
	
	@Autowired
	private ProvincesService provinceService;
	
	@Autowired
	private RebateSummaryService rebateSummaryService;
	
	@Autowired
	private UserService userService;
	
	@Autowired
	private IntegrationService integrationService;
	
	@Autowired
	private IntegrationRuleBookService integrationRuleBookService;
	
	@Autowired
	private DictionaryService dictionaryService;
	
	@Autowired
	private TimingSmsService timingSmsService;
	
	@Autowired
	private DistributorDetailsService distributorDetailsService;
	
	@Autowired
	private SmsService smsService;
	
	@Autowired
	private COrderService cOrderService;
	
	@Autowired
	private BankCardsService bankCardsService;
	
	@Autowired
	private CustomerBankCardService bankCardService;
	
	private static SimpleDateFormat sdf = new SimpleDateFormat("MM-dd");
	
	@RequestMapping(method = RequestMethod.GET)
	public String index(Model m, HttpServletRequest request) {
		
		//view为1跳转到渠道商页面，否则客户界面
		String view = request.getParameter("view");
		String type = request.getParameter("type");
		String star = request.getParameter("star");
		String auditStatus = request.getParameter("auditStatus");
		String page = "distributor";
		
		if(StringUtils.hasText(auditStatus)){
	    	m.addAttribute("auditStatus", auditStatus);
	    }
		
		if(!StringUtils.isEmpty(type)){
			m.addAttribute("type", type);
		}
		
		if(!StringUtils.isEmpty(star)){
			m.addAttribute("star", star);
		}

		if(!StringUtils.isEmpty(view)){
			m.addAttribute("view", view);
		}
		ExampleMatcher servantMmatcher = ExampleMatcher.matching()
                .withStringMatcher(ExampleMatcher.StringMatcher.EXACT);
		Customer ex = new Customer();
		ex.setType(CustomerType.DISTRIBUTOR);
		ex.setSex(null);
		ex.setCreateTime(null);
		ex.setUpdateTime(null);
		ex.setArea(null);
		ex.setProvince(null);
		ex.setActivationStatus(null);
		ex.setCity(null);
		Example<Customer> example = Example.of(ex, servantMmatcher);
		List<Customer> distributorList = customerService.findAll(example);
		m.addAttribute("distributorList", distributorList);
		if(BaseConstant.CustomerType.DISTRIBUTOR.equals(view)){
			m.addAttribute("levels", distributorLevelService.findAll());
			m.addAttribute("servants", userService.findByType(backendType.TEACHER));
			m.addAttribute("sexList", Arrays.asList(Sex.values()));
			m.addAttribute("sourceList", Arrays.asList(Source.values()));
			
			List<AuditStatusModel> list = new ArrayList<AuditStatusModel>();
			list.add(new AuditStatusModel(AuditStatus.AUDIT_PASS_TEXT, AuditStatus.AUDIT_PASS));
			list.add(new AuditStatusModel(AuditStatus.AUDIT_REJECT_TEXT, AuditStatus.AUDIT_REJECT));
			list.add(new AuditStatusModel(AuditStatus.AUDIT_WAIT_TEXT, AuditStatus.AUDIT_WAIT));
			m.addAttribute("auditStatusList", list);
		} else{
			m.addAttribute("educationList", Arrays.asList(Education.values()));
			m.addAttribute("customerLevelList", Arrays.asList(CustomerLevel.values()));
			m.addAttribute("servants", servantService.getServant(BaseConstant.ServantType.STAFF));
			page = "customer";
		}
		m.addAttribute("provinces", provinceService.findAll());
		m.addAttribute("currentPage", request.getParameter("currentPage"));
		return page;
	}
	
	@RequestMapping(path = "/distributorEdit", method = RequestMethod.GET)
	public String distributorEdit(Model m, HttpServletRequest request) {
		ExampleMatcher servantMmatcher = ExampleMatcher.matching()
                .withStringMatcher(ExampleMatcher.StringMatcher.EXACT);
		Customer ex = new Customer();
		ex.setType(CustomerType.DISTRIBUTOR);
		ex.setSex(null);
		ex.setCreateTime(null);
		ex.setUpdateTime(null);
		ex.setArea(null);
		ex.setProvince(null);
		ex.setActivationStatus(null);
		ex.setCity(null);
		Example<Customer> example = Example.of(ex, servantMmatcher);
		List<Customer> distributorList = customerService.findAll(example);
		for(Customer dis : distributorList){
			setDistributorDetails(dis);
			dis.setDisplayName(dis.getShopName() + "(" + dis.getName() + ")");
		}
		m.addAttribute("distributorList", distributorList);
		
		m.addAttribute("levels", distributorLevelService.findAll());
		m.addAttribute("servants", userService.findByType(backendType.TEACHER));
		m.addAttribute("sexList", Arrays.asList(Sex.values()));
		m.addAttribute("sourceList", Arrays.asList(Source.values()));
		
		Integer id = request.getParameter("id") == null ? null : Integer.valueOf(request.getParameter("id"));
		Customer customer = null;
		if(id != null){
			customer = customerService.findOne(id);
			setDistributorDetails(customer);
		}else{
			customer = new Customer();
			customer.setSex(null);
		}
		List<CustomerBankCard> list = bankCardService.findByCustomerId(customer.getId());
		if(!CollectionUtils.isEmpty(list)){
			customer.setCustomerName(list.get(0).getCustomerName());
			customer.setBankCardNum(list.get(0).getBankCardNum());
		}
		
		m.addAttribute("customer", customer);
		return "distributorEdit";
	}
	
	@RequestMapping(path = "/customerEdit", method = RequestMethod.GET)
	public String customerEdit(Model m, HttpServletRequest request) {
		ExampleMatcher servantMmatcher = ExampleMatcher.matching()
                .withStringMatcher(ExampleMatcher.StringMatcher.EXACT);
		Customer ex = new Customer();
		ex.setType(CustomerType.DISTRIBUTOR);
		ex.setSex(null);
		ex.setCreateTime(null);
		ex.setUpdateTime(null);
		ex.setArea(null);
		ex.setProvince(null);
		ex.setActivationStatus(null);
		ex.setCity(null);
		Example<Customer> example = Example.of(ex, servantMmatcher);
		List<Customer> distributorList = customerService.findAll(example);
		for(Customer dis : distributorList){
			setDistributorDetails(dis);
			dis.setDisplayName(dis.getShopName() + "(" + dis.getName() + ")");
		}
		m.addAttribute("distributorList", distributorList);
		
		Integer id = request.getParameter("id") == null ? null : Integer.valueOf(request.getParameter("id"));
		Customer customer = null;
		if(id != null){
			customer = customerService.findOne(id);
		}else{
			customer = new Customer();
			customer.setSex(null);
		}
		m.addAttribute("educationList", Arrays.asList(Education.values()));
		m.addAttribute("servants", servantService.getServant(BaseConstant.ServantType.STAFF));
		m.addAttribute("customer", customer);
		m.addAttribute("sexList", Arrays.asList(Sex.values()));
		m.addAttribute("currentPage", request.getParameter("currentPage"));
		return "customerEdit";
	}
	
	@RequestMapping(path = "/customerBirthDay", method = RequestMethod.GET)
	public String birthDayIndex(Model m, HttpServletRequest request) {
		m.addAttribute("type", CustomerType.CUSTOMER);
		return "customerBirthDay";
	}
	
	@ResponseBody
	@RequestMapping(path = "/list", method = RequestMethod.GET)
	private Page<Customer> find(/*Model m,*/ Customer c, String isFromBirthday, @PageableDefault Pageable pageable, HttpServletRequest req) {
		Sort sort = new Sort(Direction.DESC, "createTime");
		Pageable page = new PageRequest(pageable.getPageNumber(), pageable.getPageSize(), sort);
		//从生日界面查询客户列表，默认查3天内的
		if(Status.VALID.equals(isFromBirthday) && StringUtils.isEmpty(c.getBirthdayBegin()) && StringUtils.isEmpty(c.getBirthdayEnd())){
			Calendar calendar = Calendar.getInstance();
			c.setBirthdayBegin(sdf.format(calendar.getTime()));
			calendar.add(Calendar.DAY_OF_MONTH, 3);
			c.setBirthdayEnd(sdf.format(calendar.getTime()));
		}
		
		String servantId = req.getParameter("servantId");
		
		if(StringUtils.hasText(servantId)){
			c.setServantId(Integer.valueOf(servantId));
		}
		
		User loginUser = (User) req.getSession().getAttribute(WebConstant.USER_SESSION_NAME);
		Integer type = CommonUtil.getLoginUserType(loginUser);
		
		if(CustomerType.DISTRIBUTOR.equals(c.getType()) && backendType.TEACHER.equals(type)){
			c.setServantId(loginUser.getId());
		}else if(CustomerType.CUSTOMER.equals(c.getType()) && backendType.TEACHER.equals(type)){
			List<Integer> distributorIdList = customerService.findDistributorIdByServantId(loginUser.getId());
			if(CollectionUtils.isEmpty(distributorIdList)){
				return new PageImpl<Customer>(new ArrayList<Customer>());
			} else{
				c.setDistributorIdList(distributorIdList);
			}
		}
		
		Page<Customer> result = customerService.findAll(c, page);
		
		if(!CollectionUtils.isEmpty(result.getContent())){
			for (Customer customer : result.getContent()) {
				if (customer.getServantId() != null) {
					if(CustomerType.CUSTOMER.equals(customer.getType())){
						Servant servant = servantService.findOne(customer.getServantId());
						customer.setServantName(servant == null ? "" : servant.getName());
					}else{
						User teacher = userService.findOne(customer.getServantId());
						customer.setServantName(teacher == null ? "" : teacher.getName());
					}
				}
				
				if (customer.getLevelId() != null) {
					DistributorLevel level = distributorLevelService.findOne(customer.getLevelId());
					customer.setLevelName(level == null ? "" : level.getLevelName());
				}
				
				if(customer.getRecommendDistributorId() != null){
					Customer recommendDistributor = customerService.findOne(customer.getRecommendDistributorId());
					DistributorDetails details = distributorDetailsService.findByDistributorId(customer.getRecommendDistributorId());
					customer.setRecommendDistributorName(details == null ? "" : details.getShopName());
					customer.setRecommendDistributorPhoneNo(recommendDistributor == null ? "" : recommendDistributor.getPhoneNo());
				}
				
				//渠道商
				if(BaseConstant.CustomerType.DISTRIBUTOR.equals(customer.getType())){
					DistributorDetails details = distributorDetailsService.findByDistributorId(customer.getId());
					if(details != null){
						customer.setShopName(details.getShopName());
					}
					
					RebateSummary rs = rebateSummaryService.findByRefIdAndType(customer.getId(), RebateSummaryType.DISTRIBUTOR);
					BigDecimal allRebate = BigDecimal.ZERO;
					BigDecimal allWithdrawRebate = BigDecimal.ZERO;
					BigDecimal leftRebate = BigDecimal.ZERO;
					if(rs != null){
						allRebate = rs.getAllRebate() == null ? BigDecimal.ZERO : rs.getAllRebate();
						allWithdrawRebate = rs.getAllWithdrawRebate() == null ? BigDecimal.ZERO : rs.getAllWithdrawRebate();
						leftRebate = allRebate.subtract(allWithdrawRebate);
					}
					
					customer.setAllRebate(allRebate);
					customer.setAllWithdrawRebate(allWithdrawRebate);
					customer.setLeftRebate(leftRebate);
					
					setDistributorDetails(customer);
				}
				
			}
		}
		
		return result; 
	}
	
	
	@ResponseBody
	@RequestMapping(path = "/dlist", method = RequestMethod.GET)
	private Page<Customer> findDistributor(Customer c, String isFromBirthday, @PageableDefault Pageable pageable, HttpServletRequest req) {
		Sort sort = new Sort(Direction.DESC, "createTime");
		Pageable page = new PageRequest(pageable.getPageNumber(), pageable.getPageSize(), sort);
		//从生日界面查询客户列表，默认查3天内的
		if(Status.VALID.equals(isFromBirthday) && StringUtils.isEmpty(c.getBirthdayBegin()) && StringUtils.isEmpty(c.getBirthdayEnd())){
			Calendar calendar = Calendar.getInstance();
			c.setBirthdayBegin(sdf.format(calendar.getTime()));
			calendar.add(Calendar.DAY_OF_MONTH, 3);
			c.setBirthdayEnd(sdf.format(calendar.getTime()));
		}
		
		String servantId = req.getParameter("servantId");
		
		if(StringUtils.hasText(servantId)){
			c.setServantId(Integer.valueOf(servantId));
		}
		
		User loginUser = (User) req.getSession().getAttribute(WebConstant.USER_SESSION_NAME);
		Integer type = CommonUtil.getLoginUserType(loginUser);
		
		if(CustomerType.DISTRIBUTOR.equals(c.getType()) && backendType.TEACHER.equals(type)){
			c.setServantId(loginUser.getId());
		}else if(CustomerType.CUSTOMER.equals(c.getType()) && backendType.TEACHER.equals(type)){
			List<Integer> distributorIdList = customerService.findDistributorIdByServantId(loginUser.getId());
			if(CollectionUtils.isEmpty(distributorIdList)){
				return new PageImpl<Customer>(new ArrayList<Customer>());
			} else{
				c.setDistributorIdList(distributorIdList);
			}
		}
		
		Page<Customer> result = customerService.findDAll(c, page);
		if (CollectionUtils.isEmpty(result.getContent())) {
			return result;
		}
		
		for (Customer customer : result.getContent()) {
			DistributorDetails details = distributorDetailsService.findByDistributorId(customer.getId());
			if (details != null) {
				customer.setShopName(details.getShopName());
			}

			RebateSummary rs = rebateSummaryService.findByRefIdAndType(customer.getId(), RebateSummaryType.DISTRIBUTOR);
			BigDecimal allRebate = BigDecimal.ZERO;
			BigDecimal allWithdrawRebate = BigDecimal.ZERO;
			BigDecimal leftRebate = BigDecimal.ZERO;
			if (rs != null) {
				allRebate = rs.getAllRebate() == null ? BigDecimal.ZERO : rs.getAllRebate();
				allWithdrawRebate = rs.getAllWithdrawRebate() == null ? BigDecimal.ZERO : rs.getAllWithdrawRebate();
				leftRebate = allRebate.subtract(allWithdrawRebate);
			}

			customer.setAllRebate(allRebate);
			customer.setAllWithdrawRebate(allWithdrawRebate);
			customer.setLeftRebate(leftRebate);

			setDistributorDetails(customer);
		}
		
		return result; 
	}
	
	/**
	 * 渠道商设置详细信息
	 * @param customer
	 */
	private void setDistributorDetails(Customer customer){
		DistributorDetails details = distributorDetailsService.findByDistributorId(customer.getId());
		if(details != null){
			customer.setCode(details.getCode());
			customer.setShopName(details.getShopName());
			customer.setShopArea(details.getShopArea());
			customer.setShopStaff(details.getShopStaff());
			customer.setCooperationType(details.getCooperationType());
			customer.setCooperationStartTime(details.getCooperationStartTime());
			customer.setCooperationEndTime(details.getCooperationEndTime());
			customer.setSource(details.getSource());
			customer.setRegisterTime(details.getRegisterTime());
			customer.setRemark(details.getRemark());
		}
		
		DistributorDetails recommDetails = distributorDetailsService.findByDistributorId(customer.getRecommendDistributorId());
		if(recommDetails != null){
			customer.setRecommendShopName(recommDetails.getShopName());
		}
		
		Integer customerCount = customerService.countCustomer(customer.getId());
		customer.setCustomerCount(customerCount == null ? 0 : customerCount);
	}
	
	@RequestMapping(path = "/detail/{id}", method = RequestMethod.GET)
	private String detail(@PathVariable("id") Integer id, Model m) {
		Customer customer = customerService.findOne(id);

		if (customer.getRecommendDistributorId() != null) {
			Customer recommendDis = customerService.findOne(customer.getRecommendDistributorId());
			customer.setRecommendDistributorName(recommendDis == null ? "" : recommendDis.getName());
		}
		
		if(CustomerType.DISTRIBUTOR.equals(customer.getType())){
			if (customer.getLevelId() != null) {
				DistributorLevel level = distributorLevelService.findOne(customer.getLevelId());
				customer.setLevelName(level == null ? "" : level.getLevelName());
			}
			
			customer.setAuditStatusText(AuditStatus.getText(customer.getAuditStatus()));
			
			if (customer.getServantId() != null) {
				User teacher = userService.findOne(customer.getServantId());
				customer.setServantName(teacher == null ? "" : teacher.getName());
			}
			
			RebateSummary rs = rebateSummaryService.findByRefIdAndType(customer.getId(), RebateSummaryType.DISTRIBUTOR);
			if(rs != null){
				customer.setAllRebate(rs.getAllRebate());
				customer.setAllWithdrawRebate(rs.getAllWithdrawRebate());
			}
			setDistributorDetails(customer);
			m.addAttribute("distributor", customer);
			
			return "distributorDetail";
		}else{
			
			if (customer.getServantId() != null) {
				Servant servant = servantService.findOne(customer.getServantId());
				customer.setServantName(servant == null ? "" : servant.getName());
			}
			
			customer.setAge(CommonUtil.getAge(customer.getBirthday()));
			
			m.addAttribute("customer", customer);
			m.addAttribute("sumAmount", cOrderService.findCustomerSumAmount(id));
			return "customerDetail";
		}
	}
	
	@RequestMapping(path = "/ruleIntegrationDetail/{id}", method = RequestMethod.GET)
	@ResponseBody
	private Page<IntegrationRuleBook> ruleIntegrationDetail(@PathVariable("id") Integer id, @PageableDefault Pageable pageable) {
		IntegrationRuleBook book = new IntegrationRuleBook();
		book.setCustomerId(id);
		return integrationRuleBookService.findAll(book, pageable);
	}
	
	@RequestMapping(path = "/sendSms/{id}", method = RequestMethod.GET)
	private String sendSms(@PathVariable("id") Integer id, Model m) {
		m.addAttribute("customerId", id);
		return "sendSms";
	}


	@ResponseBody
	@RequestMapping(path = "/delete/{id}", method = RequestMethod.GET)
	private void delete(@PathVariable("id") Integer id) {
		customerService.delete(id);
		customerService.updateCustomerDistributor(id);
		integrationService.deleteByCustomerId(id);
	}

	@ResponseBody
	@RequestMapping(path = "/save", method = RequestMethod.POST)
	private void save(Customer customer, DistributorDetails distributorDetails) {
		
		validateCustomer(customer);
		if(customer.getId() == null){
			customer.setLevel("1");
		}
		
		/*if(CustomerType.CUSTOMER.equals(customer.getType()) && customer.getRecommendDistributorId() == -1){
			customer.setRecommendCustomeRrId(null);
		}*/
		
		if(customer.getBirthday() != null){
			customer.setBirthdayMmdd(sdf.format(customer.getBirthday()));
		}
		
		
		if(customer.getId() == null){//保存
			
			Date date = new Date();
			
			customer.setPassword("123456");
			customer.setCreateTime(date);
			customer.setUpdateTime(date);
			if(BaseConstant.CustomerType.DISTRIBUTOR.equals(customer.getType())){
				DistributorDetails detials = distributorDetailsService.findByCode(distributorDetails.getCode());
				if(detials != null && detials.getDistributorId() != customer.getId()){
					throw new WebException(HttpStatus.BAD_REQUEST, "渠道商代理商编号重复");
				}
				customer.setAuditStatus(BaseConstant.AuditStatus.AUDIT_PASS);
			}else{
				customer.setAuditStatus(BaseConstant.AuditStatus.AUDIT_NONE);
			}
			customer = customerService.save(customer);
			
			if(BaseConstant.CustomerType.DISTRIBUTOR.equals(customer.getType())){
				RebateSummary rs = new RebateSummary();
				rs.setAllRebate(BigDecimal.ZERO);
				rs.setAllWithdrawRebate(BigDecimal.ZERO);
				rs.setAllWaitWithdrawRebate(BigDecimal.ZERO);
				rs.setCreateTime(date);
				rs.setName(customer.getName());
				rs.setRefId(customer.getId());
				rs.setType(RebateSummaryType.DISTRIBUTOR);
				
				rebateSummaryService.save(rs);
				
				distributorDetails.setDistributorId(customer.getId());
				distributorDetailsService.save(distributorDetails);
				
				saveBankCard(customer);
				
			}else if(BaseConstant.CustomerType.CUSTOMER.equals(customer.getType())){
				Integration i = new Integration();
				i.setCustomerId(customer.getId());
				i.setCreateTime(new Date());
				i.setUpdateTime(new Date());
				i.setCustomerName(customer.getName());
				i.setMobile(customer.getPhoneNo());
				i.setIntegration(BigDecimal.ZERO);
				i.setUsedIntegration(BigDecimal.ZERO);
				integrationService.save(i);
			}
			
		}else{
			Customer originalDistributor = customerService.findOne(customer.getId());
			if(originalDistributor != null){
				customer.setPassword(originalDistributor.getPassword());
			}
			if(BaseConstant.CustomerType.DISTRIBUTOR.equals(customer.getType())){
				DistributorDetails originalDetails = distributorDetailsService.findByDistributorId(customer.getId());
				if(originalDetails != null){
					distributorDetails.setId(originalDetails.getId());
				}
				distributorDetails.setDistributorId(customer.getId());
				distributorDetailsService.save(distributorDetails);
				
				
				if(originalDistributor.getLevelId() != customer.getLevelId()){
					smsService.sendFixTimeMsg(customer.getPhoneNo(), new StringBuffer(customer.getName()).append("，您的渠道商权益已变更为").append(distributorLevelService.findOne(customer.getLevelId()).getLevelName()).append("。").toString());
				}
				saveBankCard(customer);
			}
			customerService.save(customer);
		}
	}
	
	private void saveBankCard(Customer customer){
		if(StringUtils.hasText(customer.getBankCardNum())){
			if(bankCardService.findByCustomerId(customer.getId()) != null){
				bankCardService.deleteByCustomerId(customer.getId());
			}
			
			BankCards card = bankCardsService.findByBankCardBin(customer.getBankCardNum().substring(0, 6));
			CustomerBankCard bc = new CustomerBankCard();
			if(card != null){
				bc.setBankCardType(card.getBankCardType());
				bc.setBankName(card.getBankName());
			}
			
			if(bankCardService.findByDefaultCard(customer.getId()) == null){
				bc.setIsDefault(true);
			}
			bc.setCustomerId(customer.getId());
			bc.setCustomerName(customer.getCustomerName());
			bc.setCreateTime(new Date());
			bc.setStatus(BaseStatus.YES.getIndex());
			bc.setBankCardNum(customer.getBankCardNum());
			bankCardService.save(bc);
		}
	}
	
	@ResponseBody
	@RequestMapping(path = "/adjustIntegration", method = RequestMethod.POST)
	private void adjustIntegration(Integer customerId, BigDecimal integration, BigDecimal amount) {
		
		Customer customer = customerService.findOne(customerId);
		
		IntegrationRuleBook book = new IntegrationRuleBook();
		book.setCustomerId(customerId);
		book.setCustomerName(customer.getName());
		if(integration != null){
			book.setIntegration(integration);
		}else if(amount != null){
			List<Dictionary> dictList = dictionaryService.findByType(DictionaryType.INTEGRATION_AMOUNT);
			if(!CollectionUtils.isEmpty(dictList)){
				Dictionary dict = dictList.get(0);
				book.setIntegration(amount.multiply(new BigDecimal(dict.getValue())).negate());
			}
		}else{
			book.setIntegration(BigDecimal.ZERO);
		}
		
		integrationRuleBookService.save(book, IntegrationRuleCode.BACKEND_INTEGRATION);
	}
	
	@ResponseBody
	@RequestMapping(path = "/audit", method = RequestMethod.POST)
	private void audit( Integer id) {
		Customer customer = customerService.findOne(id);
		customer.setType(CustomerType.DISTRIBUTOR);
		customer.setAuditStatus(AuditStatus.AUDIT_PASS);
		customerService.save(customer);
	}
	
	@RequestMapping(path = "/consumeReport")
	private String consumeReport() {
		return "consumeReport"; 
	}
	
	@RequestMapping(path = "/integration")
	private String integration(Model m, HttpServletRequest request) {
		String rank = request.getParameter("rank");
		m.addAttribute("rank", rank);
		return "integration"; 
	}
	
	@RequestMapping(path = "/integrationList")
	@ResponseBody
	private Page<Integration> integrationList(Integration integration, @PageableDefault Pageable pageable) {
		Pageable p = new PageRequest(pageable.getPageNumber(), pageable.getPageSize(), new Sort(Direction.DESC, "integration"));
		return integrationService.findAll(integration, p);
	}
	
	@ResponseBody
	@RequestMapping(path = "/consumeReportList")
	private Page<ConsumeReport> consumeReportList(ConsumeReport report, @PageableDefault Pageable pageable) {
		return customerService.findConsumeReport(report, pageable);
	}
	
	@RequestMapping(path = "/integrationDetail/{id}")
	private String integrationDetail(Model m, @PathVariable("id") Integer id) {
		m.addAttribute("customerId", id);
		return "integrationDetail"; 
	}
	
	@ResponseBody
	@RequestMapping(path = "/integrationDetailList")
	private Page<IntegrationRuleBook> integrationDetailList(Integer id, @PageableDefault Pageable pageable) {
		IntegrationRuleBook book = new IntegrationRuleBook();
		book.setCustomerId(id);
		return integrationRuleBookService.findAll(book, pageable);
	}
	
	@ResponseBody
	@RequestMapping(path = "/saveSms", method = RequestMethod.POST)
	private void saveSms(TimingSms timingSms) {
		if(StringUtils.isEmpty(timingSms.getContent())){
			throw new WebException(HttpStatus.BAD_REQUEST, "短信内容不能为空");
		}
		
		if(timingSms.getSendTime() == null || timingSms.getHour() == null){
			throw new WebException(HttpStatus.BAD_REQUEST, "日期和时间不能为空");
		}
		
		Customer customer = customerService.findOne(timingSms.getCustomerId());
		
		Calendar c = Calendar.getInstance();
		Date now = c.getTime();
		c.setTime(timingSms.getSendTime());
		c.set(Calendar.HOUR_OF_DAY, timingSms.getHour());
		timingSms.setSendTime(c.getTime());
		//timingSms.setContent(timingSms.getContent().replace(",", "，"));
		timingSms.setContent(timingSms.getContent());
		timingSms.setCreateTime(now);
		timingSms.setUpdateTime(now);
		timingSms.setStatus(BaseConstant.Status.INVALID);
		if(CustomerType.CUSTOMER.equals(timingSms.getReceiver())){
			timingSms.setCustomerName(customer.getName());
			timingSms.setPhoneNo(customer.getPhoneNo());
		} if(CustomerType.DISTRIBUTOR.equals(timingSms.getReceiver())){
			Customer distributor = customerService.findOne(customer.getRecommendDistributorId());
			if(distributor == null){
				throw new WebException(HttpStatus.BAD_REQUEST, "该客户渠道商不存在");
			}
			timingSms.setCustomerName(distributor.getName());
			timingSms.setPhoneNo(distributor.getPhoneNo());
		}
		
		if(BaseConstant.Status.VALID.equals(timingSms.getSendNow())){
			//smsService.sendFixTimeMsg(timingSms.getPhoneNo(), new StringBuffer(timingSms.getCustomerName()).append(",").append(timingSms.getContent()).toString());
			smsService.sendFixTimeMsg(timingSms.getPhoneNo(), new StringBuffer(timingSms.getContent()).toString());
			return;
		}
		
		timingSmsService.save(timingSms);
	}
	
	
	private void validateCustomer(Customer customer){
		
		if(!StringUtils.isEmpty(customer.getPhoneNo())){
			Customer customer2 = customerService.findByPhoneNo(customer.getPhoneNo());
			if(customer2 != null && !customer2.getId().equals(customer.getId())){
				throw new WebException(HttpStatus.BAD_REQUEST, "手机号码重复！");
			}
		}
		
	}
	
	@RequestMapping(path = "/remind")
	private String remind(Model m, HttpServletRequest request) {
		String view = request.getParameter("view");
		String type = request.getParameter("type");
		
		if(!StringUtils.isEmpty(type)){
			m.addAttribute("type", type);
		}
		
		if(!StringUtils.isEmpty(view)){
			m.addAttribute("view", view);
		}
		return "remind"; 
	}
	
	@RequestMapping(path = "/star")
	private String star(Model m){
		return "star";
	}
	
	@RequestMapping(path = "/starList")
	@ResponseBody
	private Page<StarReport> starList(Model m, @PageableDefault Pageable pageable){
		List<StarReport> list = customerService.findLevelCount();
		Page<StarReport> pageList = new PageImpl<StarReport>(list, pageable, list.size());
		return pageList;
	}
}
